import os
import re
import openpyxl

def get_xmp_info(filename,propath):
    new_filepath = filename.replace(propath, "")
    with open(filename, "r") as f:
        text = f.read()

    crs_name = re.findall(r"<crs:Name>\s*<rdf:Alt>\s*<rdf:li\s+xml:lang=\"x-default\">(.*?)</rdf:li>\s*</rdf:Alt>\s*</crs:Name>", text, re.DOTALL)
    crs_group = re.findall(r"<crs:Group>\s*<rdf:Alt>\s*<rdf:li\s+xml:lang=\"x-default\">(.*?)</rdf:li>\s*</rdf:Alt>\s*</crs:Group>", text, re.DOTALL)

    return crs_name, crs_group,filename

def write_to_excel(filename, data):
    wb = openpyxl.Workbook()
    ws = wb.active

    ws.append(["文件名", "原始名称", "原始分组","新名称","新分组"])

    for row in data:
        filepath, crs_name, crs_group = row
        crs_name_str = ", ".join(crs_name) if crs_name else ""  # 将列表转换为字符串
        crs_group_str = ", ".join(crs_group) if crs_group else ""  # 将列表转换为字符串
        ws.append([filepath, crs_name_str, crs_group_str])

    wb.save(filename)

def main():
    # 指定要读取的文件目录
    dirpath = os.path.expanduser("~/Library/Application Support/Adobe/CameraRaw")
    propath=dirpath;
    # 创建一个 Excel 文件
    excel_filename = "原始预设信息.xlsx"

    # 存储所有文件的 XMP 信息
    data = []
    print("开始处理文件")  # 打印文件名
    # 遍历目录及其子目录
    for dirpath, dirnames, filenames in os.walk(dirpath):
            for filename in filenames:
                if filename.endswith(".xmp"):
                    filepath = os.path.join(dirpath, filename)
                    crs_name, crs_group,new_filepath = get_xmp_info(filepath,propath)

                    print("正在处理文件:", filepath)  # 打印文件名

                    data.append([new_filepath, crs_name, crs_group])

    # 将 XMP 信息写入 Excel 文件
    write_to_excel(excel_filename, data)

if __name__ == "__main__":
    main()
